package controllers;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

import models.Usuario;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import util.RPXUtil;

public class LoginHandler {
	private static Logger logger = Logger
			.getLogger(Application.class.getName());

	private String rpxKey;

	/**
	 * The RPX base URL.
	 */

	private static final String RPX_BASEURL = "https://rpxnow.com";

	public LoginHandler(String rpxKey) {
		this.rpxKey = rpxKey;
	}

	public Usuario execute(String rpxToken) {
		// We had to use the token_url of this servlet to get back here, and
		// the magic token is in a parameter.

		RPXUtil rpx = new RPXUtil(rpxKey, RPX_BASEURL);

		// Make an auth dom element from the xml returned by the provider.

		Element rpxAuth = rpx.authInfo(rpxToken);

		// Check if authentication failed.

		String stat = rpxAuth.getAttribute("stat");

		if (!"ok".equals(stat)) {
			String error = "User authentication failed";

			logger.info(error);

			return null;
		}

		// Generate a map of the profile attributes.

		Map<String, String> openIdMap = new HashMap<String, String>();
		Node profile = rpxAuth.getFirstChild();
		NodeList profileFields = profile.getChildNodes();

		for (int k = 0; k < profileFields.getLength(); k++) {
			Node n = profileFields.item(k);
			if (n.hasChildNodes()) {
				NodeList nFields = n.getChildNodes();
				for (int j = 0; j < nFields.getLength(); j++) {
					Node nn = nFields.item(j);
					String nodename = n.getNodeName();
					if (!nn.getNodeName().startsWith("#"))
						nodename += "." + nn.getNodeName();

					openIdMap.put(nodename, nn.getTextContent());
				}
			} else
				openIdMap.put(n.getNodeName(), n.getTextContent());
		}

		logger.info("RPX login: " + openIdMap.toString());

		Usuario objUsuario = new Usuario(openIdMap.get("identifier"), openIdMap
				.get("preferredUsername"), openIdMap
				.get("name.formatted"));

		return objUsuario;
	}
}
